package com.topfox.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.topfox.annotation.Ignore;
import com.topfox.annotation.TableField;
import com.topfox.data.DataHelper;
import com.topfox.data.Field;
import com.topfox.data.TableInfo;
import com.topfox.misc.BeanUtil;
import com.topfox.misc.Misc;

import java.util.Map;

public class DataPojo implements IBean{

    @TableField(exist = false) @JsonIgnore
    @Ignore
    transient private TableInfo tableInfo = null;
    public TableInfo tableInfo(){
        if (tableInfo == null) {
            tableInfo = TableInfo.get(this.getClass());
        }
        return tableInfo;
    }

    /**
     * 获得实体Id 解决多主键字段值用 - 号串起来
     * @return
     */
    public String dataId(){
        Map<String, Field> mapKeyFields = tableInfo().getMapIdFields();
        if (mapKeyFields.size() > 1) {
            //多主键字段值用 - 号串起来
            StringBuilder sb = new StringBuilder();
            mapKeyFields.forEach((key, field) -> sb.append(BeanUtil.getValue(tableInfo(), this, field)).append("-"));
            //去掉最后一个字符 -
            sb.setLength(sb.length()-1);
            return sb.toString();
        }else{
            if (Misc.isNull(tableInfo().getIdField())){
                throw TopException.newInstance(ResponseCode.SYS_PK_FIELD_NOT_EXIST)
                        .text(getClass().getName()," 中找不到的主键字段(必须有一个字段用@Id注解)");
            }
            return DataHelper.parseString(BeanUtil.getValue(this, tableInfo().getIdField()));
        }
    }

    /**
     * 获得实体主键值, 并检查存在空值则报错
     * @return
     */
    public String dataIdAndCheckNull(){
        String ids=dataAllId();
        if (ids == null) {
            throw TopException.newInstance(ResponseCode.DATA_KEY_ISNULL)
                    .text("主键字段",tableInfo().getIdFields(),"的值",ids,"不能为空");
        }
        return ids;
    }
    public String dataAllId(){
        String ids=dataId();
        if (Misc.isNull(ids) || ids.indexOf("-null")>=0 || ids.indexOf("null-")>=0 ) {
            return null;
        }
        return ids;
    }
}
